import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../API/user/user.dart';
import 'login.dart';

class RegisterController extends GetxController {
  // 状态管理变量
  RxBool showPassword1 = false.obs;
  RxBool showPassword2 = false.obs;
  RxString phone = ''.obs;
  RxString name = ''.obs;
  RxString password1 = ''.obs;
  RxString password2 = ''.obs;
  RxString studentId = ''.obs;
  Rx<String?> campus = Rx<String?>(null);// 修改为可空类型
  RxString code = ''.obs;
  RxInt countdown = 0.obs;
  RxBool isCodeSent = false.obs;

  late Timer timer;

  // 发送验证码
  Future<bool> sendCode(String phone) async {
    if (phone.length != 11) {
      Get.snackbar("错误", "手机号必须为11位数字");
      return false;
    }

    final response = await ApiService.sendCode(phone);
    final int code = response["code"];

    if (code == 40011) {
      Get.snackbar("成功", "验证码已发送", snackPosition: SnackPosition.TOP);
      return true;
    } else {
      Get.snackbar(
        "错误",
        response['message'] ?? "发送失败",
        duration: const Duration(seconds: 5),
        snackPosition: SnackPosition.TOP,
      );
      return false;
    }
  }

  // 开始倒计时
  void startCountdown() {
    countdown.value = 60;
    isCodeSent.value = true;

    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (countdown.value == 0) {
        timer.cancel();
        isCodeSent.value = false;
      } else {
        countdown.value--;
      }
    });
  }

  // 注册逻辑
  Future<void> registerIn() async {
    if (validateForm()) {
      final response = await ApiService.register(
        phone.value,
        name.value,
        password1.value,
        studentId.value,
        campus.value!,
        code.value,
      );

      if (response["code"] == 10011) {
        Get.offAll(LoginPage());
        Get.snackbar("成功", "注册成功", snackPosition: SnackPosition.BOTTOM);
      } else {
        Get.snackbar(
          "错误",
          "注册失败: ${response['message']}",
          duration: const Duration(seconds: 5),
        );
      }
    }
  }

  // 表单验证
  bool validateForm() {
    if (phone.value.isEmpty || phone.value.length != 11) {
      Get.snackbar("错误", "请输入正确的手机号");
      return false;
    }
    if (name.value.isEmpty) {
      Get.snackbar("错误", "昵称不能为空");
      return false;
    }
    if (password1.value.isEmpty || password1.value.length < 6) {
      Get.snackbar("错误", "密码最少六个字符");
      return false;
    }
    if (password2.value.isEmpty || password2.value != password1.value) {
      Get.snackbar("错误", "两次密码不一致");
      return false;
    }
    if (studentId.value.isEmpty || studentId.value.length != 10) {
      Get.snackbar("错误", "学号必须为10位数字");
      return false;
    }
    if (!['北洋园', '卫津路'].contains(campus.value)) {
      Get.snackbar("错误", "请选择有效的校区");
      return false;
    }
    if (code.value.isEmpty || code.value.length != 4) {
      Get.snackbar("错误", "验证码必须为4位");
      return false;
    }
    return true;
  }

  // 清除定时器
  @override
  void onClose() {
    timer.cancel();
    super.onClose();
  }
}

class RegisterPage extends StatelessWidget {
  const RegisterPage({super.key});

  @override
  Widget build(BuildContext context) {
    final RegisterController controller = Get.put(RegisterController());

    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        backgroundColor: const Color(0xFF0088FF),
        foregroundColor: Colors.white,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () {
            Get.back();
          },
        ),
      ),
      body: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Color(0xFF0088FF), Colors.cyanAccent],
          ),
        ),
        child: ListView(
          padding: EdgeInsets.all(45),
          children: [
            const Text(
              'Welcome',
              style: TextStyle(
                color: Colors.white,
                fontSize: 32,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 40),
            _buildForm(controller),
            const SizedBox(height: 40),
            ElevatedButton(
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.white,
                foregroundColor: Colors.blue,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20),
                ),
                padding: const EdgeInsets.symmetric(horizontal: 80),
              ),
              onPressed: controller.registerIn,
              child: const Text('注册'),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildForm(RegisterController controller) {
    return Form(
      child: Column(
        children: [
          _buildPhoneField(controller),
          const SizedBox(height: 20),
          _buildNameField(controller),
          const SizedBox(height: 20),
          _buildPasswordField(controller, isConfirm: false),
          const SizedBox(height: 20),
          _buildPasswordField(controller, isConfirm: true),
          const SizedBox(height: 20),
          _buildStudentIdField(controller),
          const SizedBox(height: 20),
          _buildCampusDropdown(controller),
          const SizedBox(height: 20),
          _buildVerificationCodeSection(controller),
        ],
      ),
    );
  }

  Widget _buildPhoneField(RegisterController controller) {
    return  TextFormField(
      decoration: const InputDecoration(
        labelText: '手机号',
        hintText: '请输入11位手机号',
        labelStyle: TextStyle(color: Colors.white),
        hintStyle: TextStyle(color: Colors.white),
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.white),
        ),
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.white),
        ),
      ),
      keyboardType: TextInputType.phone,
      style: const TextStyle(color: Colors.white),
      onChanged: (value) => controller.phone.value = value,
    );
  }

  Widget _buildNameField(RegisterController controller) {
    return TextFormField(
      decoration: const InputDecoration(
        labelText: '昵称',
        hintText: '请输入昵称',
        labelStyle: TextStyle(color: Colors.white),
        hintStyle: TextStyle(color: Colors.white),
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.white),
        ),
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.white),
        ),
      ),
      style: const TextStyle(color: Colors.white),
      onChanged: (value) => controller.name.value = value,
    );
  }

  Widget _buildPasswordField(RegisterController controller, {required bool isConfirm}) {
    return Obx(() => TextFormField(
      decoration: InputDecoration(
        labelText: isConfirm ? '确认密码' : '密码',
        hintText: isConfirm ? '请确认密码' : '请输入密码',
        labelStyle: const TextStyle(color: Colors.white),
        hintStyle: const TextStyle(color: Colors.white),
        suffixIcon: IconButton(
            icon: Icon(
              (isConfirm?controller.showPassword2.value:controller.showPassword1.value)
                  ? Icons.visibility_off
                  : Icons.visibility,
              color: Colors.white,
            ),
            onPressed:(isConfirm?controller.showPassword2.toggle:controller.showPassword1.toggle)
        ),
        enabledBorder: const UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.white),
        ),
        focusedBorder: const UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.white),
        ),
      ),
      style: const TextStyle(color: Colors.white),
      obscureText: isConfirm ? !controller.showPassword2.value : !controller.showPassword1.value,
      onChanged: (value) {
        if (isConfirm) {
          controller.password2.value = value;
        } else {
          controller.password1.value = value;
        }
      },
    ));
  }

  Widget _buildStudentIdField(RegisterController controller) {
    return  TextFormField(
      decoration: const InputDecoration(
        labelText: '学号',
        hintText: '请输入学号',
        labelStyle: TextStyle(color: Colors.white),
        hintStyle: TextStyle(color: Colors.white),
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.white),
        ),
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.white),
        ),
      ),
      style: const TextStyle(color: Colors.white),
      keyboardType: TextInputType.phone,
      onChanged: (value) => controller.studentId.value = value,
    );
  }

  Widget _buildCampusDropdown(RegisterController controller) {
    return Obx(() => DropdownButtonFormField<String>(
      decoration: const InputDecoration(
        labelText: '校区',
        labelStyle: TextStyle(color: Colors.white),
        hintStyle: TextStyle(color: Colors.white),
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.white),
        ),
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.white),
        ),
      ),
      style: const TextStyle(color: Colors.white),
      dropdownColor: Colors.cyan,
      items: ['北洋园', '卫津路']
          .map((e) => DropdownMenuItem(value: e, child: Text(e)))
          .toList(),
      value: controller.campus.value,
      onChanged: (value) => controller.campus.value = value!,
    ));
  }

  Widget _buildVerificationCodeSection(RegisterController controller) {
    return Row(
      children: [
        Expanded(
          child: TextFormField(
            decoration: const InputDecoration(
              labelText: '验证码',
              labelStyle: TextStyle(color: Colors.white),
              hintStyle: TextStyle(color: Colors.white),
              enabledBorder: UnderlineInputBorder(
                borderSide: BorderSide(color: Colors.white),
              ),
              focusedBorder: UnderlineInputBorder(
                borderSide: BorderSide(color: Colors.white),
              ),
            ),
            style: const TextStyle(color: Colors.white),
            onChanged: (value) => controller.code.value = value,
          ),
        ),
        const SizedBox(width: 10),
        SizedBox(
          width: 120,
          child: Obx(()=>
              ElevatedButton(
                style: ElevatedButton.styleFrom(
                  backgroundColor: controller.isCodeSent.value
                      ? Colors.grey
                      : (controller.phone.value.length == 11
                      ? Colors.blue
                      : Color(0xCD9E9E9E)),
                ),
                onPressed: () async {
                  if (!controller.isCodeSent.value && controller.phone.value.length == 11) {
                    if (await controller.sendCode(controller.phone.value)) {
                      controller.startCountdown();
                    }
                  } else {
                    Get.snackbar("错误", "请检查手机号格式");
                  }
                },
                child: Text(
                  controller.isCodeSent.value ? '${controller.countdown.value}秒后重发' : '获取验证码',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: controller.isCodeSent.value ? 12 : 14,
                  ),
                ),
              ),
          ),
        ),
      ],
    );
  }
}